package cn.echcz.register

import akka.actor.{Actor, ActorRef, ActorSelection, ActorSystem, Props}
import com.typesafe.config.ConfigFactory

import scala.concurrent.duration._

/**
  * 服务提供者
  * @param id 服务id
  * @param health 服务健康值
  * @param rHost 注册中心地址
  * @param rPort 注册中心端口
  */
class Server(val id: String, val health: Int, rHost: String, rPort: String) extends Actor {
  // 设置心跳发送间隔为10秒
  val HEARTBEAT_INTERVAL = 10000
  var rSelection: ActorSelection = _
  val REGISTER_SUCCESS = "register_success"
  val HEARTBEAT = "heartbeat"

  // 初始化
  override def preStart(): Unit = {
    // 获取注册中心的actor
    rSelection = context.actorSelection(s"akka.tcp://registerActorSystem@$rHost:$rPort/user/registerActor")
    // 向注册中心发送注册信息
    rSelection ! ServerInfo(id, health)
  }

  override def receive: Receive = {
    case REGISTER_SUCCESS => {
      println(s"${id}注册成功")
      // 定期向自己发送心跳信息
      import context.dispatcher
      context.system.scheduler.schedule(0 millis, HEARTBEAT_INTERVAL millis, self, HEARTBEAT)
    }
    case HEARTBEAT => {
      // 中转心跳信息
      rSelection ! (HEARTBEAT, id)
    }
  }
}

object Server{
  def apply(host: String, port: String, id: String, health: Int, rHost: String, rPort: String): ActorRef = {
    // 设置actorSystem的配置
    val configSetting =
      s"""
         |akka.actor.provider = "akka.remote.RemoteActorRefProvider"
         |akka.remote.netty.tcp.hostname = "$host"
         |akka.remote.netty.tcp.port = "$port"
       """.stripMargin
    val config = ConfigFactory.parseString(configSetting)
    // 创建ActorSystem
    val serverActorSystem = ActorSystem("serverActorSystem", config)
    serverActorSystem.actorOf(Props(new Server(id, health, rHost, rPort)), "serverActor")
  }
}
